package com.gzbd.login.shiro;

import com.gzbd.login.jwt.JwtTokenUtil;
import com.gzbd.login.jwt.TokenType;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionIdGenerator;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Objects;

/**
 * session id 生成器
 *
 * @author :ys
 * @date :2023-07-26 9:48
 */
public class SystemSessionIdGenerator implements SessionIdGenerator {
    public static final String SESSION_ID_KEY = "userId";


    private static final SystemSessionIdGenerator INSTANCE = new SystemSessionIdGenerator();

    /**
     * jwt 工具, 用于解析token
     */
    private JwtTokenUtil jwtTokenUtil;


    private SystemSessionIdGenerator() {
    }

    public static SystemSessionIdGenerator getInstance() {
        return INSTANCE;
    }

    public void tokenUtilInject(JwtTokenUtil jwtTokenUtil){
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Override
    public Serializable generateId(Session session) {
        String key = (String) session.getAttribute(SESSION_ID_KEY);
        if(ObjectUtils.isEmpty(key)){
            key = extractUserId();
        }
        return key;
    }

    /**
     * 从token中获取userId
     * @return 当前请求携带token的userId
     */
    public String extractUserId(){
        if(jwtTokenUtil == null){
            return "";
        }
        try {
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
                    .getRequest();
            String token = request.getHeader("token");
            return jwtTokenUtil.getUsernameFromToken(TokenType.USER.toString(), token);
        }catch (Exception e){
        }
        return "";
    }

}
